package pl.org.lutra.planner.gui.util;

import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;

public class TimeFormat extends NumberFormat {
    private static final long serialVersionUID = -5478788846966291705L;
    
    @Override
    public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
        toAppendTo.append(formatTime(number));
        return toAppendTo;
    }
    
    @Override
    public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) {
        toAppendTo.append(formatTime(number));
        return toAppendTo;
    }
    
    private Object formatTime(Number number) {
        if (number == null) {
            return "0";
        } else {
            float fValue = number.floatValue();
            int minutes = (int) fValue;
            int seconds = (int) ((fValue % 1) * 60);
            
            if (seconds > 9) {
                return minutes + ":" + seconds;
            } else if (seconds > 0) {
                return minutes + ":0" + seconds;
            } else {
                return Integer.toString(minutes);
            }
            
        }
    }
    
    @Override
    public Number parse(String source, ParsePosition parsePosition) {
        throw new UnsupportedOperationException("not implemented");
    }
    
}
